package before

import (
	"github.com/labstack/echo"
	"m-project-admin/app/entity"
	"m-project-admin/app/manager"
	"net/http"
	"strings"
	"unicode/utf8"
)

// 中间件拦截登录权限
func InterceptLoginPermissions(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		path := c.Path()

		// 资源文件放过
		if path == "/*" {
			return next(c)
		}

		// sso接口放过
		if strings.HasPrefix(path, "/ssoLogin") || strings.HasPrefix(path, "/ssoLogout") || strings.HasPrefix(path, "/ssoCheck") {
			return next(c)
		}
		// sso接口放过
		if strings.HasPrefix(path, "/ssoAccountProfile") || strings.HasPrefix(path, "/ssoAccountProfiles") || strings.HasPrefix(path, "/ssoSearchAdmin") {
			return next(c)
		}
		// sso接口放过
		if strings.HasPrefix(path, "/ssoAccountList") || strings.HasPrefix(path, "/ssoSearchAccountPremissions") {
			return next(c)
		}

		// SSO登录接口放过
		if strings.HasPrefix(path, "/ssoDoLogin") {
			return next(c)
		}

		// 登录接口放过
		if strings.HasPrefix(path, "/doLogin") {
			return next(c)
		}

		// 登录页面
		if strings.HasPrefix(path, "/login") {
			adminId := manager.GetCurrentAdminId(&c)
			if adminId != "" && (utf8.RuneCountInString(adminId) == 24) { // 已登录跳转到首页
				return c.Redirect(http.StatusFound, "/")
			} else { // 未登录放过，前往登录页
				return next(c)
			}
		}

		// 拦截ajax
		xRequestedWith := c.Request().Header.Get("X-Requested-With")
		if xRequestedWith == "XMLHttpRequest" {
			adminId := manager.GetCurrentAdminId(&c)
			if adminId == "" || (utf8.RuneCountInString(adminId) != 24) { // 未登录提示未登录
				return c.JSON(http.StatusOK, entity.Response{En: 400, Em: "😞请先登录😞"})
			}
		}

		// 其他页面
		adminId := manager.GetCurrentAdminId(&c)
		if adminId == "" || (utf8.RuneCountInString(adminId) != 24) {
			return c.Redirect(http.StatusFound, "/login")
		}

		return next(c)
	}
}
